package com.ccx.coachsite.ui.softmgr;

import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.os.HandlerThread;
import android.os.IBinder;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.ccx.coachsite.R;
import com.ccx.coachsite.downloadmgr.DownloadItem;
import com.ccx.coachsite.downloadmgr.DownloadService;
import com.ccx.coachsite.ui.CommonAppView;
import com.ccx.coachsite.util.GraphicUtils;
import com.ccx.coachsite.util.LogUtil;
import com.ccx.coachsite.util.SUtil;

public class SoftMgrDownloadingView extends CommonAppView implements UncaughtExceptionHandler{


	private ListView lv_list;
	private LinearLayout ll_loading; //正在加载。。。
	private LinearLayout ll_no_data; //未找数据显示的提示
	private Button btn_nodata_reflash; //未找到数据显示的刷按钮
	
	/**
	 * 正在下载的任务集合
	 */
	private List<DownloadItem> mItems;
	private TextView tv_downloading;
	
	private Context mContext;
	private DownloadAdapter mAdapter;
	private Bitmap mDefaultBitmap;
	
	private DownloadStatusReceiver mDownloadStatusReceiver;//下载状态变化监听器
	private DownloadService mDownloadService;//下载服务对象
	private DownloadServiceConnection mDlServiceConnection;//下载服务绑定器
	
	private boolean mIsLoading=false;//是否正在加载
	private final int EVENT_COMMON=20000;
	private final int EVENT_FRIST_LOADING=20001;
    public static int REQUEST_CODE=1009;
	
    private boolean bAttachedToWindow = false;
    
	private Runnable mRunLoadIcon;
	private Runnable mRunLoadInfo;
	private Handler mTHandler;
	private HandlerThread mHandlerThread;
	private Handler mEventHandler=new Handler(){

		@Override
		public void handleMessage(Message msg) {
			ll_loading.setVisibility(View.GONE);
			switch(msg.what)
			{
			//第一次加载结束
			case EVENT_FRIST_LOADING:
				if(mItems!=null&&mItems.size()>0)
				{
					mAdapter.notifyDataSetChanged();
					String dlingPrefix=mContext.getString(R.string.common_on_downloading);//"正在下载"
					StringBuffer sb=new StringBuffer();
					sb.append(dlingPrefix).append("(").append(mItems.size()).append(")");
					tv_downloading.setText(sb.toString());
				}else{//当前没有下载任务
					
					TextView tv_nodata_main=(TextView) ll_no_data.findViewById(R.id.tv_nodata_main);
					tv_nodata_main.setText(mContext.getText(R.string.common_no_downloading));
					tv_nodata_main.setCompoundDrawablesWithIntrinsicBounds(null, null, null, null);
					ll_no_data.setVisibility(View.VISIBLE);
				}
				mIsLoading=false;	
				break;
			case EVENT_COMMON:
				mAdapter.notifyDataSetChanged();
				break;
			}
			
		}
		
	};
	
	/**
	 * 下载进度改变的handler,用于注册到下载服务中，实现实时跟踪进度
	 */
	private Handler mDownloadingHandler=new Handler(){
		private long oldTime = 0;
		@Override
		public void handleMessage(Message msg) {
			long curTime = System.currentTimeMillis();
			if(curTime - oldTime > 1000){
				oldTime = curTime;
				if(mAdapter!=null)
					mAdapter.notifyDataSetChanged();
			}
		}
	};
	
	
	public SoftMgrDownloadingView(Context context, HashMap<String, Object> initParaMap) {

		super(context);
		
		addView(R.layout.download_mgr_downloading);
		mContext=context;
		Drawable defDrawable=getResources().getDrawable(R.drawable.soft_mgr_defualt_icon);
		mDefaultBitmap=((BitmapDrawable)defDrawable).getBitmap();
		
		mHandlerThread=new HandlerThread("thread");
        mHandlerThread.start();
        mTHandler=new Handler(mHandlerThread.getLooper());
		mItems=new ArrayList<DownloadItem>();
		//绑定下载服务
		mDlServiceConnection=new DownloadServiceConnection();
		Intent serviceIntent=new Intent(mContext,DownloadService.class);
		mContext.getApplicationContext().bindService(serviceIntent, mDlServiceConnection, Context.BIND_AUTO_CREATE);
		
        //注册下载状态变化监听
		IntentFilter dlStatusFilter=new IntentFilter();
		dlStatusFilter.addAction(DownloadService.DOWNLOAD_STATUS_CHANGE_RECEIVER);
		mDownloadStatusReceiver=new DownloadStatusReceiver();
		mContext.registerReceiver(mDownloadStatusReceiver, dlStatusFilter);
		
		initView();
	}
	
	private void initView()
	{
		lv_list=(ListView) findViewById(R.id.lv_list);
		ll_loading=(LinearLayout) findViewById(R.id.ll_loading);
		tv_downloading=(TextView)findViewById(R.id.tv_downloading);
		ll_no_data=(LinearLayout)findViewById(R.id.ll_no_data);
		btn_nodata_reflash=(Button)ll_no_data.findViewById(R.id.btn_nodata_reflash);
		
		btn_nodata_reflash.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View v) {
				loadDownloadedData();
			}
		});
	}
	
	/**
	 * 加载正在下载的数据
	 */
	private synchronized void loadDownloadedData()
	{
		if(mIsLoading)
			return;
		mIsLoading=true;
		ll_no_data.setVisibility(View.GONE);
		ll_loading.setVisibility(View.VISIBLE);
		
		mRunLoadInfo=new Runnable() {
			
			@Override
			public void run() {
				try {
					
					/* ------------------正在下载的---------------------------- */
					List<DownloadItem> dlingItems=null;
					long begin=System.currentTimeMillis();
					while(true)
					{
						if(mDownloadService!=null)
							dlingItems=mDownloadService.getDownloadingList();
						if(dlingItems!=null&&dlingItems.size()>0)
						{
							synchronized (mItems) {
								mItems.clear();
								mItems.addAll(dlingItems);
							}
							break;
						}
						long end=System.currentTimeMillis();
						if((end-begin)>1000) //超过两秒未结束循环，自动退出
							break;
					}
					
						
					
					sendMessage(EVENT_FRIST_LOADING);
					//加载图标
					loadIcon();
				} catch (Exception e) {
					e.printStackTrace();
				}
				
			}
		};
		
		mTHandler.post(mRunLoadInfo);
		mAdapter=new DownloadAdapter(mContext,mItems);
		lv_list.setAdapter(mAdapter);
	
	}
	
	/**
	 * 加载软件 的图标
	 */
	private void loadIcon() 
	{
		mRunLoadIcon=new Runnable() {
			
			public void run() {
				PackageManager pm=mContext.getPackageManager();
				for(int i=0;i<mItems.size();i++)
				{
					DownloadItem item=mItems.get(i);
					if(item==null)
						continue;
					String iconPath=item.getIconPath()==null?"":item.getIconPath();
					File iconFile=new File(iconPath);
					Bitmap tmpBmp=null;
					if(iconFile.exists()){
						//存在图标缓存文件，则加载它
						WindowManager windowManager = (WindowManager)mContext.getSystemService(Context.WINDOW_SERVICE);
						tmpBmp=GraphicUtils.getImageFile(item.getIconPath(), windowManager.getDefaultDisplay());
					}else{
						//已安装的情况，从安装的应用中获取图标
						Drawable d = null;
						try {
							d = pm.getApplicationIcon(item.getPkgName());
						} catch (NameNotFoundException e) {
							d=null;
						}
						
						if(d==null)//取不到图标，设置为默认图标
							tmpBmp=mDefaultBitmap;
						else
							tmpBmp=((BitmapDrawable)d).getBitmap();
							
					}
					item.setIcon(tmpBmp);
					
					if((i+1)%10==0||i==mItems.size()-1)
					{
						sendMessage(EVENT_COMMON);
					}
				}//end for
				
			}
		};
				
		mTHandler.post(mRunLoadIcon);
					
	}
	
	

	@Override
	public void onAttachedToWindow() {
		//注册下载服务
		if(mDownloadService!=null)
			mDownloadService.registHandler(mDownloadingHandler);
		loadDownloadedData();
		
		super.onAttachedToWindow();
	}

	@Override
	public void onDetachedFromWindow() {
		//注销下载服务
		if(mDownloadService!=null)
			mDownloadService.unregistHandler(mDownloadingHandler);
		
		super.onDetachedFromWindow();
	}

	
	/**
     * 清除缓存
     */
	@Override
    public void clearCache()
    {
    	try {
    		
    		//解除下载服务的绑定
    		mContext.unbindService(mDlServiceConnection);
    		//注销下载状态监听
    		mContext.unregisterReceiver(mDownloadStatusReceiver);
    		
    		mTHandler.removeCallbacks(mRunLoadIcon);
    		mTHandler.removeCallbacks(mRunLoadInfo);
        	for(DownloadItem item:mItems)
        	{
        		if(item!=null)
        		{
        			Bitmap icon=item.getIcon();
        			if(icon!=null&&!icon.isRecycled())
        				icon.recycle();
        		}
        	}
        	if(mItems!=null){
        		mItems.clear();
        		mItems=null;
        	}
		} catch (Exception e) {
			e.printStackTrace();
		}
    	
    }
		
	@Override
	public void uncaughtException(Thread thread, Throwable ex) {
		ex.printStackTrace();
	}
	
	private void sendMessage(int what)
	{
		Message msg=new Message();
		msg.what=what;
		mEventHandler.sendMessage(msg);
	}
	/*-------------------------------内部类区------------------------------------------*/
	    
    /**
     * 下载状态改变监听器
     */
    private class DownloadStatusReceiver extends BroadcastReceiver{

		@Override
		public void onReceive(Context context, Intent intent) {
			DownloadItem dItem=(DownloadItem) intent.getSerializableExtra(DownloadItem.EXTRA_ME);
			if(dItem==null)
				return;
			if(dItem.getStatus() == DownloadItem.STATUS_DOWNLOADED){
				for(DownloadItem item:mItems)
				{
					if(item.getPkgName().equals(dItem.getPkgName()))
					{
						mItems.remove(item);
						sendMessage(EVENT_FRIST_LOADING);
						break;
					}
				}
			}else{
				sendMessage(EVENT_COMMON);
			}
		}
    	
    }//end DownloadStatusReceiver
    

    /**
     * 绑定服务连接器
     *
     */
    class DownloadServiceConnection implements ServiceConnection
    {

    	@Override
    	public void onServiceConnected(ComponentName arg0, IBinder binder) {
    		LogUtil.d("DownloadServiceConnection", "Service Connection Success");
    		//连接成功执行
    		//开始加载数据
    		mDownloadService = ((DownloadService.LocalBinder) binder).getService();
    		if(mDownloadService!=null)
    			//注册进度跟踪的handler
    			mDownloadService.registHandler(mDownloadingHandler);
    		loadDownloadedData();
    	}

    	@Override
    	public void onServiceDisconnected(ComponentName arg0) {
    		LogUtil.d("DownloadServiceConnection", "Service Connection Filed");
    		//连接失败执行
    		sendMessage(EVENT_FRIST_LOADING);
    	}
    }// DownloadServiceConnection
    
    /**
     * 列表的Adapter
     */
    private class DownloadAdapter extends BaseAdapter{
    	
    	private Context mCtx;
    	private List<DownloadItem> mItemList;
    	private LayoutInflater mInflater;
    	public DownloadAdapter(Context ctx, List<DownloadItem> items) {
    		mItemList=items;
    		mCtx=ctx;
    		mInflater=(LayoutInflater) mCtx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    	}

		@Override
		public int getCount() {
			return mItemList.size();
		}
		@Override
		public Object getItem(int position) {
			return mItemList.get(position);
		}
		@Override
		public long getItemId(int position) {
			return position;
		}
		
		@Override
    	public View getView(int position, View convertView, ViewGroup parent){
    		DownloadItem item=mItemList.get(position);
    		Holder holder=null;
    		View view=null;
    		if(convertView==null)
    		{
    			view=mInflater.inflate(R.layout.download_list_item, null);
    			holder=new Holder();
    			holder.im_imageInfo=(ImageView) view.findViewById(R.id.im_imageInfo);
    			holder.tv_title=(TextView) view.findViewById(R.id.tv_title);
    			holder.tv_version=(TextView) view.findViewById(R.id.tv_version);
    			holder.tv_size=(TextView) view.findViewById(R.id.tv_size);
    			holder.pb_progress=(ProgressBar) view.findViewById(R.id.pb_progress);
    			holder.tv_time=(TextView) view.findViewById(R.id.tv_time);
    			holder.tv_delete=(TextView)view.findViewById(R.id.tv_delete);
    			holder.tv_oper=(TextView) view.findViewById(R.id.tv_oper);
    			holder.tv_rate=(TextView) view.findViewById(R.id.tv_rate);
    			holder.ll_progress=(LinearLayout) view.findViewById(R.id.ll_progress);
    			view.setTag(holder);
    			
    		}else
    			view=convertView;
    		
    		String versionPrefix=mContext.getText(R.string.common_version)+":";
    		String sizePrefix=mContext.getText(R.string.common_size)+":";
    		
    		holder=(Holder) view.getTag();
    		holder.im_imageInfo.setImageBitmap(item.getIcon());
    		holder.tv_title.setText(item.getTitle());
    		holder.tv_version.setText(versionPrefix+item.getAvailVersion());
    		String size=SUtil.getComputerSize(item.getFileBytes(), 2);
    		holder.tv_size.setText(sizePrefix+size);
    		holder.tv_time.setTextColor(Color.BLACK);
    		
    		ClickListener clickListener=new ClickListener(position);
//    		holder.tv_delete.setVisibility(View.GONE);
    		holder.tv_oper.setOnClickListener(clickListener);
    		
    		switch(item.getStatus()){
    		case DownloadItem.STATUS_DOWNLOAD_PAUSE:
    			holder.tv_delete.setText(R.string.common_button_continue);
    			break;
    		case DownloadItem.STATUS_DOWNLOADING:
    			holder.tv_delete.setText(R.string.common_button_pause);
    			break;
    		case DownloadItem.STATUS_DOWNLOAD_FAILED:
    			holder.tv_delete.setText(R.string.common_button_retry);
    			break;
    		}

    		holder.tv_delete.setOnClickListener(clickListener);
    		
    		switch(item.getStatus())
    		{
    		//正在下载
    		case DownloadItem.STATUS_DOWNLOADING:
    		case DownloadItem.STATUS_DOWNLOAD_PAUSE:
    			long downloadBytes=item.getDownloadBytes();
    			long fileBytes=item.getFileBytes();
    			String downLoadSize;
    			downLoadSize=SUtil.getComputerSize(downloadBytes, 2);
    			holder.tv_size.setText(sizePrefix+downLoadSize+"/"+SUtil.getComputerSize(fileBytes, 2));
    			holder.tv_time.setVisibility(View.GONE);
    			holder.ll_progress.setVisibility(View.VISIBLE);
    			holder.pb_progress.setMax(100);
    			int per=(int)((float)downloadBytes/fileBytes*100);
    			holder.pb_progress.setProgress(per);
    			holder.tv_rate.setText(per+"%");
    			holder.tv_oper.setText(mContext.getString(R.string.common_button_del));
    			break;
    		//下载失败
    		case DownloadItem.STATUS_DOWNLOAD_FAILED:
    			holder.ll_progress.setVisibility(View.GONE);
    			holder.tv_time.setVisibility(View.VISIBLE);
    			holder.tv_time.setTextColor(Color.RED);
    			holder.tv_time.setText(mContext.getString(R.string.common_download_failed));
    			holder.tv_oper.setText(mContext.getString(R.string.common_button_del));
    			break;
    		}
    		
    		return view;
    	}
    	
    	private class Holder{
    		public ImageView im_imageInfo;
    		public TextView tv_title;
    		public TextView tv_version;
    		public TextView tv_size;
    		public LinearLayout ll_progress;
    		public ProgressBar pb_progress;
    		public TextView tv_time;
    		public TextView tv_delete;
    		public TextView tv_oper;
    		public TextView tv_rate;
    	}
    	
    	private class ClickListener implements OnClickListener{
    		private DownloadItem mAdapterItem;
    		
    		public ClickListener(int pos){
    			mAdapterItem=mItemList.get(pos);
    		}
    		
    		@Override
    		public void onClick(View v) {
    			if(v.getId()==R.id.tv_oper)
    			{
    				switch(mAdapterItem.getStatus())
        			{
        			//正在下载,则取消下载
        			case DownloadItem.STATUS_DOWNLOADING:
        			case DownloadItem.STATUS_DOWNLOAD_PAUSE:
        			case DownloadItem.STATUS_DOWNLOAD_FAILED:
        				String tipMsg=mContext.getString(R.string.common_downloaded_cancel_confirm);
        				new AlertDialog.Builder(mContext).setTitle(R.string.common_tip)
        				.setMessage(tipMsg.replace("{0}", mAdapterItem.getTitle()))
        				.setPositiveButton(R.string.common_button_confirm, new DialogInterface.OnClickListener() {
        					
        					@Override
        					public void onClick(DialogInterface dialog, int which) {
        						if(mItemList.contains(mAdapterItem)){
	        						Intent cancelIntent=new Intent(DownloadService.RECEIVER_CANCEL_DOWNLOAD);
	                				cancelIntent.putExtra(DownloadItem.EXTRA_ME, mAdapterItem);
	                				mContext.sendBroadcast(cancelIntent);
	                				mItemList.remove(mAdapterItem);
	                				sendMessage(EVENT_FRIST_LOADING);
        						}
        					}
        				}).setNegativeButton(R.string.common_button_cancell, null).create().show();
        				break;
        			}//end switch
    			}else if(v.getId() == R.id.tv_delete){
    				switch(mAdapterItem.getStatus())
        			{
        			//正在下载,则暂停下载
        			case DownloadItem.STATUS_DOWNLOADING:
        				DownloadService.pauseItem(mAdapterItem,mContext);
        				sendMessage(EVENT_COMMON);
        				break;
        			//暂停状态,则继续下载
        			case DownloadItem.STATUS_DOWNLOAD_PAUSE:
        				DownloadService.continueItem(mAdapterItem,mContext);
        				sendMessage(EVENT_COMMON);
        				break;
        			//下载失败,则重试下载
        			case DownloadItem.STATUS_DOWNLOAD_FAILED:
        				Intent intent=new Intent(mContext,DownloadService.class);
    					intent.putExtra(DownloadItem.EXTRA_ME, mAdapterItem);
    					mContext.startService(intent);
        				break;
        			}
    			}
    		}// end onClick
    	}// end ClickListener
    }// end InstallAdapter
}